<?php

namespace App\Providers;

use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Route;

class RouteServiceProvider extends ServiceProvider
{
    /**
     * The path to the "adminNamespace" route for your application.
     *
     * Typically, users are redirected here after authentication.
     *
     * @var string
     */
    protected const adminNamespace = 'App\Http\Controllers\Admin';
    protected const apiNamespace   = 'App\Http\Controllers\Api';
    protected const homeNamespace   = 'App\Http\Controllers\Home';

    /**
     * Define your route model bindings, pattern filters, and other route configuration.
     *
     * @return void
     */
    public function boot()
    {
        $this->configureRateLimiting();

//        $this->routes(function () {
//            Route::middleware('web')
//                ->group(base_path('routes/web.php'));
//        });

        // 后台路由
        $this->mapAdminRoutes();
        // Api路由
        $this->mapApiRoutes();
        // Home路由
        $this->mapHomeRoutes();
    }

    protected function mapAdminRoutes()
    {
        $prefix = config('admin.prefix');
        Route::prefix($prefix)
            ->namespace(self::adminNamespace)
            ->middleware(['web', 'admin.agent'])
            ->group(base_path('routes/admin/framework/routes.php'));
    }

    protected function mapApiRoutes()
    {
        Route::prefix('api')
            ->namespace(self::apiNamespace)
            ->middleware(['api.agent'])
            ->group(base_path('routes/api/framework/routes.php'));
    }

    protected function mapHomeRoutes()
    {
        Route::prefix('/')
            ->namespace(self::homeNamespace)
            ->middleware(['web','home.agent'])
            ->group(base_path('routes/home.php'));
    }

    /**
     * Configure the rate limiters for the application.
     *
     * @return void
     */
    protected function configureRateLimiting()
    {
        RateLimiter::for('api', function (Request $request) {
            return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
        });
    }
}
